<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="84px">
      <el-form-item label="专场名称" prop="sessionName">
        <el-input
          v-model="queryParams.sessionName"
          placeholder="请输入专场名称"
          clearable
          style="width: 200px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="时间范围" prop="timeRange">
        <el-date-picker
          v-model="dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          style="width: 240px"
          @change="handleDateRangeChange"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="专场状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable style="width: 140px">
          <el-option label="未开始" value="0" />
          <el-option label="进行中" value="1" />
          <el-option label="已结束" value="2" />
          <el-option label="已取消" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['demo:session:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['demo:session:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['demo:session:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['demo:session:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sessionList" @selection-change="handleSelectionChange" border stripe>
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column label="专场ID" align="center" prop="sessionId" width="80" />
      <el-table-column label="专场名称" align="center" prop="sessionName" min-width="150" :show-overflow-tooltip="true" />
      <el-table-column label="专场封面" align="center" width="80">
        <template slot-scope="scope">
          <el-image
            :src="getImageUrl(scope.row.coverImage)"
            :preview-src-list="scope.row.coverImage ? [getImageUrl(scope.row.coverImage)] : []"
            style="width: 50px; height: 50px; border-radius: 4px;"
            fit="cover"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" style="font-size: 20px;"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="时间信息" align="center" width="200">
        <template slot-scope="scope">
          <div style="font-size: 12px;">
            <div>开始：{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}') }}</div>
            <div style="margin-top: 4px;">结束：{{ parseTime(scope.row.endTime, '{y}-{m}-{d} {h}:{i}') }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template slot-scope="scope">
          <el-tag :type="statusTagType(scope.row.status)" size="mini">
            {{ statusFormat(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="专场描述" align="center" prop="sessionDesc" min-width="200" :show-overflow-tooltip="true" />
      <el-table-column label="专场图片" align="center" width="150">
        <template slot-scope="scope">
          <div class="image-list">
            <template v-if="scope.row.images">
              <el-image
                v-for="(img, index) in scope.row.images.split(',')"
                :key="index"
                :src="getImageUrl(img)"
                :preview-src-list="getImageList(scope.row.images)"
                style="width: 40px; height: 40px; margin: 2px; border-radius: 4px; cursor: pointer;"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" style="font-size: 16px;"></i>
                </div>
              </el-image>
            </template>
            <template v-else>
              <span class="no-data">暂无图片</span>
            </template>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="150" fixed="right">
        <template slot-scope="scope">
          <el-tooltip content="预览" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handlePreview(scope.row)"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="修改" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['demo:session:edit']"
            ></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['demo:session:remove']"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改拍卖专场对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="专场名称" prop="sessionName">
          <el-input v-model="form.sessionName" placeholder="请输入专场名称" />
        </el-form-item>
        <el-form-item label="专场描述" prop="sessionDesc">
          <el-input v-model="form.sessionDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="专场封面图片" prop="coverImage">
          <image-upload v-model="form.coverImage"/>
        </el-form-item>
        <el-form-item label="专场图片(逗号隔开)" prop="images">
          <el-input v-model="form.images" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="专场开始时间" prop="startTime">
          <el-date-picker clearable
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择专场开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="专场结束时间" prop="endTime">
          <el-date-picker clearable
            v-model="form.endTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择专场结束时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="主分类ID" prop="categoryId">
          <el-input v-model="form.categoryId" placeholder="请输入主分类ID" />
        </el-form-item>
        <el-form-item label="默认规则ID" prop="ruleId">
          <el-input v-model="form.ruleId" placeholder="请输入默认规则ID" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSession, getSession, delSession, addSession, updateSession } from "@/api/demo/session";

export default {
  name: "Session",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 拍卖专场表格数据
      sessionList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sessionName: null,
        sessionDesc: null,
        coverImage: null,
        images: null,
        startTime: null,
        endTime: null,
        categoryId: null,
        ruleId: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sessionName: [
          { required: true, message: "专场名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "专场开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "专场结束时间不能为空", trigger: "blur" }
        ],
      },
      dateRange: [],
      // 基础API URL
      baseApiUrl: "http://localhost:1024"
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询拍卖专场列表 */
    getList() {
      this.loading = true;
      listSession(this.queryParams).then(response => {
        this.sessionList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sessionId: null,
        sessionName: null,
        sessionDesc: null,
        coverImage: null,
        images: null,
        startTime: null,
        endTime: null,
        categoryId: null,
        ruleId: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.sessionId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加拍卖专场";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sessionId = row.sessionId || this.ids
      getSession(sessionId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改拍卖专场";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.sessionId != null) {
            updateSession(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSession(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sessionIds = row.sessionId || this.ids;
      this.$modal.confirm('是否确认删除拍卖专场编号为"' + sessionIds + '"的数据项？').then(function() {
        return delSession(sessionIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('demo/session/export', {
        ...this.queryParams
      }, `session_${new Date().getTime()}.xlsx`)
    },
    statusFormat(status) {
      const statusMap = {'0': '未开始', '1': '进行中', '2': '已结束', '3': '已取消'};
      return statusMap[status] || '未知';
    },
    statusTagType(status) {
      const typeMap = {'0': 'info', '1': 'success', '2': 'warning', '3': 'danger'};
      return typeMap[status] || 'info';
    },
    /** 日期范围变化处理 */
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.startTime = val[0];
        this.queryParams.endTime = val[1];
      } else {
        this.queryParams.startTime = null;
        this.queryParams.endTime = null;
      }
    },
    /** 预览按钮操作 */
    handlePreview(row) {
      // 这里可以实现预览功能，比如打开一个预览弹窗
      this.$modal.msgInfo("预览功能开发中");
    },
    // 获取图片URL
    getImageUrl(url) {
      if (!url) return '';
      // 判断是否已经是完整URL
      if (url.startsWith('http')) {
        return url;
      }
      // 添加基础URL前缀
      return this.baseApiUrl + url;
    },
    // 获取图片列表
    getImageList(imagesStr) {
      if (!imagesStr) return [];
      return imagesStr.split(',')
        .map(img => this.getImageUrl(img))
        .filter(url => url.trim() !== '');
    }
  }
};
</script>

<style scoped>
.el-table .warning-row {
  background: oldlace;
}
.el-table .success-row {
  background: #f0f9eb;
}
.image-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 4px;
}
.el-table td.el-table__cell {
  padding: 8px 0;
}
.el-tag + .el-tag {
  margin-left: 4px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background-color: #f5f7fa;
  color: #909399;
}
.no-data {
  font-size: 12px;
  color: #909399;
  display: inline-block;
  padding: 10px 0;
}
</style>
